package com.my.aop;

import com.my.service.OperationLogService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/**
 * @author marshal
 * @date 2021-06-08
 * <p>
 * 日志处理切面
 * <p>
 */
@Aspect
@Component
public class WebLogAspect extends CommonPoints {
    private final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    private OperationLogService operationLogService;

    /**
     *  在方法执行前打印日志
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before(value = "inWebLayer()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印URL （http://localhost:8080/user/save）
        logger.info("URL : " + request.getRequestURL().toString());
        // 打印请求方法（POST）
        logger.info("HTTP_METHOD : " + request.getMethod());
        // 打印IP  0:0:0:0:0:0:0:1
        logger.info("IP : " + request.getRemoteHost());
        // 打印方法（com.my.web.UserController.save）
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // 打印入参（[User(name=Tom, age=12)]）
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     *  方法执行后，输出返回数据
     *
     * @param joinPoint
     * @param result
     * @throws Throwable
     */
    @AfterReturning(returning = "result", pointcut = "inWebLayer()")
    public void doAfterReturning(JoinPoint joinPoint, Object result) throws Throwable {
//        // 接收到请求，记录请求内容
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        // 处理完请求，返回内容
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        //获取切入点所在的方法
//        Method method = signature.getMethod();
//        //将返回值转换成map集合
//        R r = (R) result;
//        OperationLogAnnotation annotation = method.getAnnotation(OperationLogAnnotation.class);
//        // 保存操作日志
//        if (Objects.nonNull(annotation)) {
//            OperationLog log = OperationLog.builder()
//                    .user("admin")
//                    .module(annotation.module())
//                    .ip(request.getRemoteAddr())
//                    .type(annotation.type().getType())
//                    .description(annotation.description())
////                    .result(r.getMsg())
//                    .build();
//            operationLogService.save(log);
//        }
        // RESPONSE : R(code=200, message=success, data=User(super=BaseBean(id=3, deleted=null, createTime=Fri Nov 26 11:49:23 CST 2021, updateTime=Fri Nov 26 11:49:23 CST 2021), name=Rose, age=14))
        logger.info("RESPONSE : " + result);
    }
}
